package com.webserver.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 响应对象
 * 该类的一个实例用于表示 HTTP 协议规定的响应
 * 一个响应应由是三部分构成:状态行,响应头,响应正文
 */
public class HttpServletResponse {
    private Socket socket;
    //状态行相关信息
    private int statusCode = 200;//状态代码
    private String statusReason = "OK"; //状态描述
    //响应头相关信息

    //响应正文相关信息
    private File contentFile; // 响应正文对应的实体文件

    public HttpServletResponse(Socket socket) {
        this.socket = socket;
    }
    /**
     *  该方法会将当前响应对象内容以标准的 HTTP 响应格式通过 socket 获取的输出流发送给对应的客户端
     */
    public void response() throws IOException {
        // 发送状态行
        sendStatusLine();
        // 发送响应头
        sendHeaders();
        // 发送响应正文
        sendContent();
    }

    // 发送状态行
    private void sendStatusLine () throws IOException{
        println("HTTP/1.1" + " " + statusCode + " " + statusReason);
    }
    // 发送响应头
    private void sendHeaders() throws IOException {
        // 发送响应头  Content-Type: text/html(CRLF)
        println("Content-Type: text/html");
        // Content-Length: 2546(CRLF)
        println("Content-Length: " + contentFile.length());
        // 单独发送回车+换行表达响应头发送完毕
        println("");
    }
    // 发送响应正文
    private void sendContent() throws IOException {
        OutputStream out = socket.getOutputStream();
        try (
                FileInputStream fis = new FileInputStream(contentFile)
        ){
           byte[] data = new byte[1024*10];
           int len ;
           while ((len = fis.read(data)) != -1) {
               out.write(data,0,len);
           }
        }
    }

    private void println(String line) throws IOException {
        OutputStream os = socket.getOutputStream();
        os.write(line.getBytes(StandardCharsets.UTF_8));
        os.write(13);
        os.write(10);
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
    }
}
